<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c"%>
<%@ taglib uri="/WEB-INF/tld/ui.tld" prefix="ui"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>还款申请</title>
<jsp:include page="../../import.jsp" flush="true" />
</head>
<body class="iframeBody">
	<div class="Wrapper">
		<div id="pageInTab" class="pageInTab">
			<form id="fnc_prj_pay_schfm_form">
				<div class="fieldset1 tabel_col tabel_col_s clearFix">
					<div class="caption">
						<span class="title">项目基础信息</span>
					</div>
					<div class="fieldBox col_50">
						<div class="label">项目名称</div>
						<div class="field">
							<span name="FNCPRJNM" id="FNCPRJNM" >${bscinfo.FNCPRJNM}</span>
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">项目编号</div>
						<div class="field">
							<span name="FNCPRJID" id="FNCPRJID" >${bscinfo.FNCPRJID}</span>
							<input type="hidden" id="payschid" name="payschid" value="${bscinfo.SCHDID}">
							<input type="hidden" id="oper" name="oper" value="${oper}">
							<input type="hidden" id="jrnlid" name="jrnlid" value="${jrnlid}">
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">创建日期</div>
						<div class="field">
							<span name="CRTTM" id="CRTTM" >${bscinfo.CRTTM}</span>
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">融资机构</div>
						<div class="field">
							<span name="FUNDRASINSNM" id="FUNDRASINSNM" >${bscinfo.FUNDRASINSNM}</span>
							<input type="hidden" id="fundrasinsid" name="fundrasinsid" value="${bscinfo.FUNDRASINSID}">
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">融资方案</div>
						<div class="field">
							<span name="FNCSCMNM" id="FNCSCMNM" >${bscinfo.FNCSCMNM}</span>
							<input type="hidden" id="fncscmid" name="fncscmid" value="${bscinfo.FNCSCMID}">
							<input type="hidden" id="repytp" name="repytp" value="${bscinfo.REPY_TP}">
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">项目金额</div>
						<div class="field">
							<span name="FNCPRJAMT" id="FNCPRJAMT" >${bscinfo.FNCPRJAMT}</span>
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">实际融资金额</div>
						<div class="field">
							<span name="FNCFIAMT" id="FNCFIAMT" >${bscinfo.ACFIAMT}</span>
							<input type="hidden" id="famt" name="famt" value="${bscinfo.ACFIAMT}">
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">支付表数量</div>
						<div class="field">
							<span name="PAYCNT" id="PAYCNT" >${bscinfo.PAYCNT}</span>
						</div>
					</div>
				</div>
				<div class="fieldset1 tabel_col tabel_col_s clearFix">
					<div class="caption">
						<span class="title">账户信息</span>
					</div>
					<div class="fieldBox col_50">
						<div class="label">机构收款账户</div>
						<div class="field">
							<%-- <input name="recvAcc" id="recvAcc" type="text" class="ui-textbox" value="${raccno}"  validate="{required:true}"> --%>
							<a href='#' onclick='showInsAcc(${bscinfo.RACCID})'> <font color='blue'>${raccno}</font></a>
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">我司付款账户</div>
						<div class="field">
							<%-- <input name="payAcc" id="payAcc" type="text" class="ui-textbox" value="${paccno}" > --%>
							<a href='#' onclick='showSysAcc(${bscinfo.PACCID})'> <font color='blue'>${paccno}</font></a>
						</div>
					</div>
				</div>	
				<div class="fieldset1 tabel_col tabel_col_s clearFix">
					<div class="caption">
						<span class="title">融资端费用</span>
					</div>
					<div class="fieldBox col_100">
							<div id="cost0" class="sq-grid">
							</div>
					</div>
				</div>
				<div class="fieldset1 tabel_col tabel_col_s clearFix">
					<div class="caption">
						<span class="title">还款明细</span>
					</div>
					<div class="fieldBox col_100">
							<div id="cost1" class="sq-grid">
							</div>
					</div>
				</div>
				<div class="fieldset1 tabel_col tabel_col_s clearFix">
					<div class="fieldBox col_100">
						<div class="label">还款本金合计</div>
						<div class="field">
							<input name="sumFeeAmt" id="sumFeeAmt" type="text" class="ui-textbox" disabled="disabled">
						</div>
					</div>
				</div>
			</form>
		</div>
		<div class="btnsBox" id="ss">
			<span id="repay_list_add_btn_id" class="sq-button sq-button-round" >保存</span>
		</div>
	</div>
<!-- 嵌入账户详情 -->
<jsp:include page="../mrgnmanageinfo/showAcc.jsp"></jsp:include>
	<script type="text/javascript">
	var griddata0,griddata1,cur_pd,defaultchecked;
	$(function () {
		f_initDatePicker();
		initCost0Grid();
		initDetlGrid();
    	$("#fnc_prj_pay_schfm_form").ligerForm({
    		validate:true
        });
    	saveFncPrjPayEvent();
	});
    function f_initDatePicker(){
    	var actpymtdt = $("#actpymtdt").val();

		var stDateStr = "";
		if(null != actpymtdt && actpymtdt != ""){
        	$("#actpymtdt").ligerDateEditor({ 
        		showTime: true, labelWidth: 100, labelAlign: 'left' ,format: 'yyyy-MM-dd',
        		onChangeDate : function(value){
        			$("#actpymtdt").val(value);
        		}
        	});
			var date = new Date(actpymtdt);
			stDateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
        	$("#actpymtdt").ligerGetDateEditorManager().setValue(stDateStr);
		}
    }
    function initCost0Grid()
    {
    	var jrnlid = $("#jrnlid").val();
    	griddata0 = $("#cost0").ligerGrid({
	    	url: '<%=path%>/rfbase/fncprjpaysch/initCost0JrnlGrid.do?jrnlid='+jrnlid,
	    	method : 'get',
            columns: [
                { display: '费用名称', name: 'COST_NM', width: 160, type: 'text'},
                { display: '应还金额', name: 'FEE_AMT', width: 160, type: 'float'},
                { display: '已还金额', name: 'PAID_UP_AMT', width: 160, type: 'float'},
                { display: '剩余金额', name: 'AR_AMT', width: 160, type: 'float',
                    totalSummary:
                    {
                        render: function (suminf, column, cell)
                        {
                            return '<div>合计:' + suminf.sum + '</div>';
                        },
                        align: 'left'
                    }
    			},
                { display: '应还金额浮动', name: 'FLOAT_AMT',type: 'float', 
                    editor: { type: 'float' }, align: 'left', width: 160
                },
                { display: '本次还款额', name: 'ACTUAL_AMT',type: 'float', 
                    editor: { type: 'float' }, align: 'left', width: 160,
                    totalSummary:
                    {
                        render: function (suminf, column, cell)
                        {
                            return '<div>' + suminf.sum + '</div>';
                        },
                        align: 'left'
                    }
                },
                { display: '备注', name: 'FEE_REM', width: 200, type: 'text',align: 'left'
                },
                { display: '实际付款时间', name: 'ACT_PYMT_DT', type: 'date',render:renderDate,format: 'yyyy-MM-dd',editor: { type: 'date' } },
                { display: '实际还款金额', name: 'ACT_PYMT_AMT',type: 'float', 
                    editor: { type: 'float' }, align: 'left', width: 300,
                },
                { display: '机构收款账号', name: 'rcvpymtAccNoHtml', width: 150, type: 'text'}, 
                { display: '我司付款账户', name: 'payAccNm', width: 200, type: 'text'},
                { display: '我司付款账号', name: 'payAccNoHtml', width: 200, type: 'text'},
                { display: '逻辑序号', name: 'ID',width:0, align:'left', hide:true}
            ],
            enabledEdit: true, isScroll: true,rownumbers:true,
            width: '100%',height:160,checkbox:true,usePager:false,
            onBeforeEdit: f_onBeforeEdit0,
            onBeforeCheckRow: function (checked, data, rowindex, rowobj)
            {
                if (data.AR_AMT == 0){
                	alert('本期还款已结清，无需勾选还款!');
                    return false;
                }
                return true;
            },
            onBeforeSubmitEdit: f_onBeforeSubmitEdit0,
            onSelectRow : function (rowdata, rowid, rowobj)
            {
                var manager = $("#cost0").ligerGetGridManager();
        		var aramt = rowdata.FEE_AMT-rowdata.PAID_UP_AMT+rowdata.FLOAT_AMT;
                if (aramt == 0){
            		manager.unselect(rowid);
                }
				if(aramt != 0 && (rowdata.ACTUAL_AMT == 0 || rowdata.ACTUAL_AMT == null)){
	      			manager.updateRow(rowdata,{
	      				ACTUAL_AMT: aramt
	    	        });
                }
            },
            onUnSelectRow  : function (rowdata, rowid, rowobj)
            {
                var manager = $("#cost0").ligerGetGridManager();
    	        manager.updateRow(rowdata,{
    	        	ACTUAL_AMT: 0,
    	        	FLOAT_AMT: 0,
    	        	FEE_REM: ''
    	        });
            },
            onAfterShowData: f_onAfterShowData0
        });
    }
	
    function initDetlGrid()
    {
    	var jrnlid = $("#jrnlid").val();
    	griddata1 = $("#cost1").ligerGrid({
	    	url: '<%=path%>/rfbase/fncprjpaysch/initDetlJrnlGrid.do?jrnlid='+jrnlid,
	    	method : 'get',
            columns: [
            { display: '期数', name: 'payPd', width: 50, type: 'int' },
            { display: '应还款项', name: 'feeClsCd',width: 150, type: 'text',
                render: function (item)
                {
                    if (parseInt(item.feeClsCd) == 1) return '本金';
                    if (parseInt(item.feeClsCd) == 2) return '利息';
                    if (parseInt(item.feeClsCd) == 3) return '超额抵押';
                    return '其他费用';
                }},
            { display: '还款日', width: 150, name: 'payDt',render:renderDate},
            { display: '应还金额', name: 'feeAmt', width: 160, type: 'float',
                editor: { type: 'float' }, align: 'left', width: 300,
                totalSummary:
                {
                    render: function (suminf, column, cell)
                    {
                        return '<div>' + suminf.sum + '</div>';
                    },
                    align: 'left'
                }
            },
            { display: '已还金额', name: 'paidUpAmt', width: 160, type: 'float'},
            { display: '剩余金额', name: 'arAmt', width: 160, type: 'float',
                totalSummary:
                {
                    render: function (suminf, column, cell)
                    {
                        return '<div>合计:' + suminf.sum + '</div>';
                    },
                    align: 'left'
                }
			},
            { display: '应还金额浮动', name: 'floatAmt',type: 'float', 
                editor: { type: 'float' }, align: 'left', width: 160,
            },
            { display: '本次还款额', name: 'actualAmt',type: 'float', 
                editor: { type: 'float' }, align: 'left', width: 160,
                totalSummary:
                {
                    render: function (suminf, column, cell)
                    {
                        return '<div>' + suminf.sum + '</div>';
                    },
                    align: 'left'
                }
            },
            { display: '备注', name: 'feeRem', width: 200, type: 'text',align: 'left'
            },
            { display: '实际付款时间', name: 'actPymtDt', type: 'date',render:renderDate,format: 'yyyy-MM-dd',editor: { type: 'date' } },
            { display: '实际还款金额', name: 'actPymtAmt',type: 'float', 
                editor: { type: 'float' }, align: 'left', width: 300,
            },
            { display: '机构收款账号', name: 'rcvpymtAccNoHtml', width: 150, type: 'text' }, 
            { display: '我司付款账户', name: 'payAccNm', width: 200, type: 'text'},
            { display: '我司付款账号', name: 'payAccNoHtml', width: 200, type: 'text'},
            { display: '逻辑序号', name: 'id',width:0, align:'left', hide:true},
            { display: '关联明细主表序号', name: 'schDId',width:0, align:'left', hide:true}
            ],
            enabledEdit: true, isScroll: true,rownumbers:true,
            onBeforeEdit: f_onBeforeEdit,
            onBeforeCheckRow: function (checked, data, rowindex, rowobj)
            {
            	console.log("data.payPd > cur_pd:"+data.payPd+"__"+cur_pd);
                if (data.arAmt == 0){
                	alert('本期还款已结清，无需勾选还款!');
                    return false;
                }
                if(data.payPd > cur_pd+1){
                	alert('只能修改下一期次还款!');
                    return false;
                }
                return true;
            },
            onBeforeSubmitEdit: f_onBeforeSubmitEdit,
            onSelectRow : function (rowdata, rowid, rowobj)
            {
                if(defaultchecked.indexOf(rowdata.id)<0){
                	return;
                }
                var manager = $("#cost1").ligerGetGridManager();
        		var aramt = rowdata.feeAmt-rowdata.paidUpAmt+rowdata.floatAmt;
                if (aramt == 0){
            		manager.unselect(rowid);
                }
				if(aramt != 0 && (rowdata.actualAmt == 0 || rowdata.actualAmt == null)){
	      			manager.updateRow(rowdata,{
	    	        	actualAmt: aramt
	    	        });
                }
            },
            onUnSelectRow  : function (rowdata, rowid, rowobj)
            {
                var manager = $("#cost1").ligerGetGridManager();
    	        manager.updateRow(rowdata,{
    	        	actualAmt: 0,
    	        	floatAmt: 0,
    	        	feeRem: ''
    	        });
            },
            onAfterShowData: f_onAfterShowData,
            width: '100%',height:350,checkbox:true,usePager:false
        });
    }

    //表格列待编辑事件，只允许编辑金额为0且选中的记录
    function f_onBeforeEdit(e)
    { 
        var manager = $("#cost1").ligerGetGridManager();
		var rowdata = manager.getRow(e.rowindex);
		var aramt = rowdata.arAmt;
		if(aramt == 0){
        	alert('该期次还款已结清，无需修改!');
			return false;
		}
        if(defaultchecked.indexOf(rowdata.id)<0 ){
        	if(e.column.name == "feeAmt"){
				if(manager.isSelected(e.rowindex)){
					return true;
				}else{
					alert('请选中该记录后，再编辑!'); 
					return false;
				}
        	}else{
        		return false;
        	}
        }else{
	        if (e.column.name == "actualAmt" || e.column.name == "floatAmt" || e.column.name == "feeRem" ||  e.column.name == "feeAmt"){
				if(manager.isSelected(e.rowindex)){
					return true;
				}else{
					alert('请选中该记录后，再编辑!'); 
					return false;
				}
	        }
        }
        return true;
    }
    //限制录入金额范围
    function f_onBeforeSubmitEdit(e)
    { 
            if (e.column.name == "actualAmt")
            {
                var manager = $("#cost1").ligerGetGridManager();
        		var rowdata = manager.getRow(e.rowindex);
        		//var aramt = rowdata.feeAmt-rowdata.paidUpAmt+rowdata.floatAmt;
        		var aramt = accAdd(rowdata.feeAmt-rowdata.paidUpAmt,rowdata.floatAmt);
        		if(manager.isSelected(e.rowindex) && (e.value == null || e.value =="")){
                	alert('选中记录应还金额不能为空!');
        			return false;
    			}
        		if(aramt<e.value){
                	alert('还款金额不能大于剩余未还（应还+当前浮动-已还）!');
        			return false;
        		}else{
        			return true;
        		}
            }
            if (e.column.name == "floatAmt")
            {
                var manager = $("#cost1").ligerGetGridManager();
        		var rowdata = manager.getRow(e.rowindex);
        		var f1 = Number(rowdata.arAmt)+Number(e.value);
        		var f2 = Number(rowdata.arAmt)*2;
        		if(f1<=0 || f1>f2){
        			alert('浮动金额不能超出正负剩余未还款额!');
        			return false;
        		}else{
        			//调整浮动后，刷新本次还款为剩余应还公式计算结果
            		var aramt = Number(rowdata.feeAmt-rowdata.paidUpAmt+e.value);
    	      		manager.updateRow(rowdata,{
    	    	        	actualAmt: aramt.toFixed(2)
    	    	        });
        			return true;
        		}
            }
            return true;
    }
    
    //加载默认选中行
    function f_onAfterShowData(currentData){
    	console.log("f_onAfterShowData");
    	var sumFeeAmt = 0;
    	if(currentData!=null){
	    	var arr = eval(currentData);      
	        var rows = arr.Rows;
	        var manageri = $("#cost1").ligerGetGridManager();
	        defaultchecked = "";
	        for(var i=0;i<rows.length;i++){
	        	if(rows[i].actualAmt!=null && rows[i].actualAmt != 0){
	        		manageri.select(i);
	        		cur_pd = rows[i].payPd;
	        		defaultchecked = defaultchecked + rows[i].id;
	        	}
	        	if(rows[i].feeClsCd == 1){
	        		sumFeeAmt = accAdd(sumFeeAmt , rows[i].feeAmt);
	        	}
	        }
	        $("#sumFeeAmt").val(sumFeeAmt);
    	}
    	console.log("f_onAfterShowData"+defaultchecked);
    }
    
    //保存事件
    function saveFncPrjPayEvent(){
        	$("#repay_list_add_btn_id").click(function(event) {
        		save();
        	});
    };
	function cancelBtn(){
		 var TAB=top.mainApp.parentTab;
       var currentTabid=TAB.getSelectedTabItemID();
		 top.tab.removeTabItem(currentTabid);		
	}
	//格式化时间
	function renderDate(rowdata, index, value){
		var dateStr = "";
		if(null != value){
			var date = new Date(value);
			dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
		}
		return dateStr;
	}	

	//加法函数，用来得到精确的加法结果
	//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
	//调用：accAdd(arg1,arg2)
	//返回值：arg1加上arg2的精确结果
	function accAdd(arg1,arg2){
	 var r1,r2,rr,m,maxlen,result;
	 try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
	 try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}	 
	 console.log("length:"+r1+"_"+r2);
	 maxlen = Math.max(r1,r2);
	 m=Math.pow(10,maxlen);
	 console.log("Math.pow:"+m);
	 result = (arg1*m+arg2*m)/m;
	 console.log("result:"+result);
	 return result.toFixed(maxlen);
	}
	//保存更新
	function save(){
        var manager0 = $("#cost0").ligerGetGridManager();
        var rows0 = manager0.getSelectedRows();
        var arr0 = eval(rows0);
        
        var manager1 = $("#cost1").ligerGetGridManager();
        var rows1 = manager1.getSelectedRows();
        var arr1 = eval(rows1);
        
        var allData = manager1.getData();
        var allArr = eval(allData);
		var sumFeeAmt = 0;
        var actTolAmt = $("#famt").val();
 		if($("#repytp").val() == 1){
	 		if($("#recvAcc").val()=='' || $("#payAcc").val()==''){
				alert("请维护收付款账户！");
				return;
			} 			
 		}else{
	 		if($("#payAcc").val()==''){
				alert("请维护付款账户！");
				return;
			} 
 		}

    	var flag1 = 0;
        for(var i=0;i<arr1.length;i++){
        	var adt = arr1[i].actPymtDt;
        	var aamt = arr1[i].actPymtAmt;
        	if(defaultchecked.indexOf(arr1[i].id)>=0 && (adt == null || aamt == null)){
        		flag1=flag1+1;
        	}
        	if(flag1>0){
        		alert("请录入原选中还款记录的实际还款时间和实际还款金额！");
        		return;
        	}
        }
        for(var i=0;i<arr1.length;i++){
        	if(arr1[i].payPd <= cur_pd 
        			&& (Number(arr1[i].actualAmt)>accAdd(Number(arr1[i].feeAmt),Number(arr1[i].floatAmt))-Number(arr1[i].paidUpAmt) )){
        		alert("本次还款金额不能大于剩余未还（应还+当前浮动-已还）！");
        		return;
        	}
        } 
        for(var i=0;i<allArr.length;i++){
        	if(allArr[i].feeClsCd == 1){
        		//sumFeeAmt = sumFeeAmt + allArr[i].feeAmt;
        		sumFeeAmt = accAdd(sumFeeAmt , allArr[i].feeAmt);
        	}
        }
        console.log(sumFeeAmt);
        if(Number(sumFeeAmt) != Number(actTolAmt)){
        	alert("应还本金合计与实际融资金额不符！当前本金合计："+sumFeeAmt);
    		return;
        }
        var data = $("form").serializeArray();
    	var jrnlid = $("#jrnlid").val();
		if(!jrnlid)return;

 		var jsondata = '{jrnlid:'+jrnlid+',griddata0:'+JSON.stringify(arr0)+',griddata1:'+JSON.stringify(arr1)+',formdata:'+JSON.stringify(data)+'}';
    	$.ajax({
      	   type: "POST",
     	   url: "<%=path%>/rfbase/fncprjpaysch/updateBData.do",
     	   contentType: 'application/json',
     	   data: JSON.stringify(jsondata),
     	   dataType:"json",
       		success:function(msg){
    			 if(msg.msgcode == "0000"){
  					 alert("保存成功!");
  					 //cancelBtn();
       			 }else{
      				UIUtils.alertErrorHold1(msg.errormsg);
       			 }
    		}
     	});
	}
	
	 //表格列待编辑事件，只允许编辑金额为0且选中的记录
    function f_onBeforeEdit0(e)
    { 
        var manager = $("#cost0").ligerGetGridManager();
		var rowdata = manager.getRow(e.rowindex);
		var aramt = rowdata.AR_AMT;
		if(aramt == 0){
        	alert('该期次还款已结清，无需修改!');
			return false;
		}

        if (e.column.name == "ACTUAL_AMT" || e.column.name == "FLOAT_AMT")
        {
			if(manager.isSelected(e.rowindex)){
				return true;
			}else{
				alert('请选中该记录后，再编辑!'); 
				return false;
			}
        }
        return true;
    }
    //限制录入金额
    function f_onBeforeSubmitEdit0(e)
    { 
        if (e.column.name == "ACTUAL_AMT")
        {
            var manager = $("#cost0").ligerGetGridManager();
    		var rowdata = manager.getRow(e.rowindex);
    		var aramt = rowdata.FEE_AMT-rowdata.PAID_UP_AMT+rowdata.FLOAT_AMT;
    		if(manager.isSelected(e.rowindex) && (e.value == null || e.value =="")){
            	alert('选中记录应还金额不能为空!');
    			return false;
			}
    		if(aramt<e.value){
            	alert('还款金额不能大于剩余金额!');
    			return false;
    		}else{
    			return true;
    		}
        }
        if (e.column.name == "FLOAT_AMT")
        {
            var manager = $("#cost0").ligerGetGridManager();
    		var rowdata = manager.getRow(e.rowindex);
    		var f1 = Number(rowdata.AR_AMT)+Number(e.value);
    		var f2 = Number(rowdata.AR_AMT)*2;
    		if(f1<=0 || f1>f2){
    			alert('浮动金额不能超出正负剩余未还款额!');
    			return false;
    		}else{
    			return true;
    		}
        }
        return true;
    }
    
    //加载默认选中行
    function f_onAfterShowData0(currentData){
    	if(currentData!=null){
	    	var arr = eval(currentData);      
	        var rows = arr.Rows;
            var manager = $("#cost0").ligerGetGridManager();
	        for(var i=0;i<rows.length;i++){
	        	if(rows[i].ACTUAL_AMT!=null && rows[i].ACTUAL_AMT != 0){
            		manager.select(i);
	        	}
	        }
    	}
    }
	</script>
</body>
</html>